<!--
  * 角色 树形结构
-->
<template>
  <div>
    <div class="tree-header">
      <p>设置租户对应的功能操作、后台管理权限</p>
      <a-button v-if="props.tenantId" type="primary" @click="saveChange" v-privilege="'system:tenant:menu:update'"> 保存 </a-button>
    </div>
    <!-- 功能权限勾选部分 -->
    <RoleTreeCheckbox :tree="tree" />
  </div>
</template>
<script setup lang="ts">
  import { inject, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import _ from 'lodash';
  import RoleTreeCheckbox from './role-tree-checkbox.vue';
  import { enterpriseApi } from '/@/api/business/oa/enterprise-api';
  import { useTenantStore } from '/@/store/modules/system/tenant';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { smartSentry } from '/@/lib/smart-sentry';

  const props = defineProps({
    tenantId: {
      type: String,
      default: null,
    },
  });

  let roleStore = useTenantStore();
  let tree = ref();

  watch(
    () => props.tenantId,
    (e) => {
      if (e) {
        getRoleSelectedMenu();
      }
    },
    { immediate: true }
  );

  async function getRoleSelectedMenu() {
    if (!props.tenantId) {
      return;
    }
    let res = await enterpriseApi.getResourceAllTree();
    if (res.success) {
      tree.value = res.data;
      if(_.isEmpty(roleStore.treeMap)){
        roleStore.initTreeMap(res.data || []);
      }
    }
    let rel = await enterpriseApi.getHasResource(props.tenantId);
    if(rel.success){
      roleStore.initCheckedData(rel.data || []);
    }
  }
  async function saveChange() {
    let checkedData = roleStore.checkedData;
    if (_.isEmpty(checkedData)) {
      message.error('还未选择任何权限');
      return;
    }
    let params = {
      tenantId: props.tenantId,
      authList: checkedData,
    };
    SmartLoading.show();
    try {
      await enterpriseApi.saveMenuTenant(params);
      message.success('保存成功');
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  }
</script>
<style scoped lang="less">
  @import './index.less';
</style>
